'use strict';

// 云对象名：invitation-service
module.exports = {
  _before: async function() {
    // 获取客户端信息
    this.clientInfo = this.getClientInfo();
    console.log('invitation-service _before 初始化完成');
  },

  /**
   * 发送邀请
   * @param {object} params - 邀请参数
   * @param {string} params.scheduleId - 比赛日程ID
   * @param {string} params.matchId - 比赛ID（系列赛ID）
   * @param {array} params.inviteeIds - 受邀用户ID数组
   * @param {string} params.position - 邀请岗位（可选）
   * @param {string} params.message - 邀请消息（可选）
   * @returns {object} 发送结果
   */
  async sendInvitations(params) {
    try {
      const { scheduleId, matchId, inviteeIds, position, message } = params;
      console.log('收到邀请发送请求，参数:', params);
      
      // 验证token
      const token = this.getUniIdToken();
      console.log('获取到token:', token);
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      console.log('Token验证结果:', verifyResult);
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const inviterId = verifyResult.data.userId;
      
      // 参数验证
      if (!scheduleId || !matchId || !inviteeIds || !Array.isArray(inviteeIds) || inviteeIds.length === 0) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }

      const db = uniCloud.database();
      
      // 验证比赛日程是否存在且当前用户是发布者
      const scheduleCollection = db.collection('match_schedules');
      const scheduleResult = await scheduleCollection.doc(scheduleId).get();
      
      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '比赛日程不存在'
        };
      }
      
      const schedule = scheduleResult.data[0];
      
      // 检查权限（兼容两种字段名）
      if (schedule.organizer_id !== inviterId) {
        return {
          code: -1,
          message: '无权限操作此比赛日程'
        };
      }

      // 获取比赛信息用于通知
      const matchCollection = db.collection('matches');
      const matchResult = await matchCollection.doc(matchId).get();
      const match = matchResult.data.length > 0 ? matchResult.data[0] : { title: '比赛' };

      // 检查用户是否存在
      const usersCollection = db.collection('users');
      const usersResult = await usersCollection.where({
        _id: db.command.in(inviteeIds)
      }).get();
      
      if (usersResult.data.length !== inviteeIds.length) {
        return {
          code: -1,
          message: '部分用户不存在'
        };
      }

      // 检查是否已经邀请过（针对该日程）
      const invitationCollection = db.collection('match_invitations');
      const existingInvitations = await invitationCollection.where({
        schedule_id: scheduleId,
        invitee_id: db.command.in(inviteeIds),
        status: db.command.in(['sent', 'accepted'])
      }).get();
      
      const existingInviteeIds = existingInvitations.data.map(inv => inv.invitee_id);
      const newInviteeIds = inviteeIds.filter(id => !existingInviteeIds.includes(id));
      
      if (newInviteeIds.length === 0) {
        return {
          code: -1,
          message: '所有用户都已被邀请过'
        };
      }

      // 设置邀请过期时间（7天后）
      const expireTime = new Date();
      expireTime.setDate(expireTime.getDate() + 7);

      // 创建邀请记录
      const invitations = newInviteeIds.map(inviteeId => ({
        schedule_id: scheduleId,
        match_id: matchId,
        inviter_id: inviterId,
        invitee_id: inviteeId,
        position: position || '',
        invitation_message: message || `诚邀您参与 ${match.title}（${schedule.date}）的裁判工作`,
        status: 'sent',
        expire_time: expireTime
      }));

      const invitationResult = await invitationCollection.add(invitations);
      
      // 发送通知
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        await notificationService.batchSendNotification({
          userIds: newInviteeIds,
          type: 'match_invitation',
          category: '比赛通知',
          title: `比赛邀请：${match.title}（${schedule.date}）`,
          content: message || `诚邀您参与 ${match.title}（${schedule.date}）的裁判工作，点击查看详情`,
          relatedId: scheduleId,
          senderId: inviterId,
          extraData: {
            schedule_id: scheduleId,
            match_id: matchId,
            match_title: match.title,
            schedule_date: schedule.date,
            position: position,
            invitation_ids: invitationResult.ids || [invitationResult.id]
          }
        });
      } catch (notifyError) {
        console.error('发送邀请通知失败:', notifyError);
        // 不影响主流程
      }

      return {
        code: 0,
        message: `成功发送 ${newInviteeIds.length} 个邀请`,
        data: {
          successCount: newInviteeIds.length,
          failCount: inviteeIds.length - newInviteeIds.length,
          alreadyInvited: existingInviteeIds.length
        }
      };

    } catch (error) {
      console.error('发送邀请失败:', error);
      return {
        code: -2,
        message: '发送邀请失败: ' + error.message
      };
    }
  },

  /**
   * 响应邀请
   * @param {object} params - 响应参数
   * @param {string} params.invitationId - 邀请ID
   * @param {string} params.response - 响应结果：accepted/declined
   * @param {string} params.message - 响应消息（可选）
   * @returns {object} 响应结果
   */
  async respondInvitation(params) {
    try {
      const { invitationId, response, message } = params;
      
      // 验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      
      // 参数验证
      if (!invitationId || !response || !['accepted', 'declined'].includes(response)) {
        return {
          code: -1,
          message: '参数不正确'
        };
      }

      const db = uniCloud.database();
      const invitationCollection = db.collection('match_invitations');
      
      // 查询邀请记录
      const invitationResult = await invitationCollection.doc(invitationId).get();
      
      if (!invitationResult.data.length) {
        return {
          code: -1,
          message: '邀请不存在'
        };
      }
      
      const invitation = invitationResult.data[0];
      
      // 验证权限
      if (invitation.invitee_id !== userId) {
        return {
          code: -1,
          message: '无权限操作此邀请'
        };
      }
      
      // 检查邀请状态
      if (invitation.status !== 'sent') {
        return {
          code: -1,
          message: '邀请已处理或已过期'
        };
      }
      
      // 检查是否过期
      if (invitation.expire_time && new Date() > new Date(invitation.expire_time)) {
        // 自动标记为过期
        await invitationCollection.doc(invitationId).update({
          status: 'expired',
          update_time: new Date()
        });
        
        return {
          code: -1,
          message: '邀请已过期'
        };
      }

      // 更新邀请状态
      await invitationCollection.doc(invitationId).update({
        status: response,
        response_time: new Date(),
        update_time: new Date()
      });

      // 如果接受邀请，需要为该日程下的所有时段创建报名记录
      if (response === 'accepted') {
        try {
          // 获取日程信息
          const scheduleCollection = db.collection('match_schedules');
          const scheduleResult = await scheduleCollection.doc(invitation.schedule_id).get();
          
          if (scheduleResult.data.length > 0) {
            const schedule = scheduleResult.data[0];
            
            // 为日程下的每个时段报名
            if (schedule.time_slots && schedule.time_slots.length > 0) {
              const matchScheduleObject = uniCloud.importObject('match-schedule-object');
              
              for (const slot of schedule.time_slots) {
                try {
                  await matchScheduleObject.applyForSlot({
                    scheduleId: invitation.schedule_id,
                    slotId: slot.slot_id,
                    position: invitation.position || '裁判',
                    message: message || '通过邀请加入'
                  });
                } catch (slotApplyError) {
                  console.error(`时段${slot.slot_id}报名失败:`, slotApplyError);
                  // 不影响其他时段的报名
                }
              }
            }
          }
        } catch (applyError) {
          console.error('自动报名失败:', applyError);
          // 不影响邀请响应的主流程
        }
      }

      // 通知邀请人
      try {
        const notificationService = uniCloud.importObject('notification-service');
        const matchCollection = db.collection('matches');
        const matchResult = await matchCollection.doc(invitation.match_id).get();
        const matchTitle = matchResult.data[0]?.title || '比赛';
        
        const responseText = response === 'accepted' ? '接受' : '拒绝';
        
        await notificationService.sendNotification({
          userId: invitation.inviter_id,
          type: 'invitation_response',
          category: '比赛通知',
          title: `邀请回复：${matchTitle}`,
          content: `用户${responseText}了您的比赛邀请`,
          relatedId: invitation.match_id,
          senderId: userId,
          extraData: {
            invitation_id: invitationId,
            response: response,
            match_id: invitation.match_id
          }
        });
      } catch (notifyError) {
        console.error('发送响应通知失败:', notifyError);
        // 不影响主流程
      }

      return {
        code: 0,
        message: response === 'accepted' ? '已接受邀请' : '已拒绝邀请',
        data: {
          invitationId: invitationId,
          response: response
        }
      };

    } catch (error) {
      console.error('响应邀请失败:', error);
      return {
        code: -2,
        message: '响应邀请失败: ' + error.message
      };
    }
  },

  /**
   * 获取邀请列表
   * @param {object} params - 查询参数
   * @param {string} params.type - 列表类型：sent-已发送, received-已接收
   * @param {string} params.status - 状态筛选（可选）
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @returns {object} 邀请列表
   */
  async getInvitationList(params) {
    try {
      const { type, status, page = 1, limit = 20 } = params;
      
      // 验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      
      // 参数验证
      if (!type || !['sent', 'received'].includes(type)) {
        return {
          code: -1,
          message: '查询类型不正确'
        };
      }

      const db = uniCloud.database();
      const invitationCollection = db.collection('match_invitations');
      
      // 构建查询条件
      const where = {};
      if (type === 'sent') {
        where.inviter_id = userId;
      } else {
        where.invitee_id = userId;
      }
      
      if (status) {
        where.status = status;
      }

      const skip = (page - 1) * limit;
      
      // 查询邀请列表
      const invitationResult = await invitationCollection
        .where(where)
        .orderBy('create_time', 'desc')
        .skip(skip)
        .limit(limit)
        .get();

      // 获取总数
      const countResult = await invitationCollection.where(where).count();

              // 获取相关的日程、比赛和用户信息
        const invitations = invitationResult.data;
        
        if (invitations.length > 0) {
          const scheduleIds = [...new Set(invitations.map(inv => inv.schedule_id))];
          const matchIds = [...new Set(invitations.map(inv => inv.match_id))];
          const userIds = [...new Set(invitations.map(inv => 
            type === 'sent' ? inv.invitee_id : inv.inviter_id
          ))];

          // 获取日程信息
          const scheduleCollection = db.collection('match_schedules');
          const scheduleResult = await scheduleCollection
            .where({ _id: db.command.in(scheduleIds) })
            .field({ _id: true, date: true, venue: true, match_id: true })
            .get();

          const scheduleMap = {};
          scheduleResult.data.forEach(schedule => {
            scheduleMap[schedule._id] = schedule;
          });

          // 获取比赛信息
          const matchCollection = db.collection('matches');
          const matchResult = await matchCollection
            .where({ _id: db.command.in(matchIds) })
            .field({ _id: true, title: true, location: true, start_date: true, end_date: true })
            .get();

          const matchMap = {};
          matchResult.data.forEach(match => {
            matchMap[match._id] = match;
          });

        // 获取用户信息
        const usersCollection = db.collection('users');
        const usersResult = await usersCollection
          .where({ _id: db.command.in(userIds) })
          .field({ _id: true, nickname: true, real_name: true, phone: true })
          .get();

        const userMap = {};
        usersResult.data.forEach(user => {
          userMap[user._id] = user;
        });

                  // 合并信息
          invitations.forEach(invitation => {
            invitation.schedule_info = scheduleMap[invitation.schedule_id] || {};
            invitation.match_info = matchMap[invitation.match_id] || {};
            invitation.user_info = userMap[type === 'sent' ? invitation.invitee_id : invitation.inviter_id] || {};
          });
      }

      return {
        code: 0,
        message: '获取邀请列表成功',
        data: {
          list: invitations,
          total: countResult.total,
          page: page,
          limit: limit,
          hasMore: countResult.total > page * limit
        }
      };

    } catch (error) {
      console.error('获取邀请列表失败:', error);
      return {
        code: -2,
        message: '获取邀请列表失败: ' + error.message
      };
    }
  },

  /**
   * 获取邀请详情
   * @param {object} params - 查询参数
   * @param {string} params.invitationId - 邀请ID
   * @returns {object} 邀请详情
   */
  async getInvitationDetail(params) {
    try {
      const { invitationId } = params;
      
      // 验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      
      // 参数验证
      if (!invitationId) {
        return {
          code: -1,
          message: '邀请ID不能为空'
        };
      }

      const db = uniCloud.database();
      const invitationCollection = db.collection('match_invitations');
      
      // 查询邀请记录
      const invitationResult = await invitationCollection.doc(invitationId).get();
      
      if (!invitationResult.data.length) {
        return {
          code: -1,
          message: '邀请不存在'
        };
      }
      
      const invitation = invitationResult.data[0];
      
      // 验证权限（只有邀请人和受邀人可以查看）
      if (invitation.inviter_id !== userId && invitation.invitee_id !== userId) {
        return {
          code: -1,
          message: '无权限查看此邀请'
        };
      }

      // 获取相关信息
      let matchInfo = {};
      let scheduleInfo = {};
      let inviterInfo = {};

      try {
        // 获取比赛信息
        const matchCollection = db.collection('matches');
        const matchResult = await matchCollection.doc(invitation.match_id).get();
        if (matchResult.data.length > 0) {
          matchInfo = matchResult.data[0];
        }

        // 获取日程信息
        const scheduleCollection = db.collection('match_schedules');
        const scheduleResult = await scheduleCollection.doc(invitation.schedule_id).get();
        if (scheduleResult.data.length > 0) {
          scheduleInfo = scheduleResult.data[0];
        }

        // 获取邀请人信息
        const usersCollection = db.collection('users');
        const userResult = await usersCollection.doc(invitation.inviter_id).get();
        if (userResult.data.length > 0) {
          const user = userResult.data[0];
          inviterInfo = {
            _id: user._id,
            nickname: user.nickname,
            username: user.username,
            real_name: user.real_name
          };
        }
      } catch (fetchError) {
        console.error('获取相关信息失败:', fetchError);
        // 不影响主流程，继续返回邀请信息
      }

      return {
        code: 0,
        message: '获取邀请详情成功',
        data: {
          invitation: invitation,
          matchInfo: matchInfo,
          scheduleInfo: scheduleInfo,
          inviterInfo: inviterInfo
        }
      };

    } catch (error) {
      console.error('获取邀请详情失败:', error);
      return {
        code: -2,
        message: '获取邀请详情失败: ' + error.message
      };
    }
  }
}; 